package com.zzc.qqchat.util;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginHandlerInterceptor implements HandlerInterceptor {
    //在请求处理的方法之前执行，放回true就通过，放回false就拦截。
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Integer loginUser = (Integer) request.getSession().getAttribute("loginUserId");
        if(request.getQueryString()==null){
            return true;
        }
        String id = request.getQueryString().substring(3);
        Integer i = null;
        if(id!=null){
            i = Integer.valueOf(id);
        }
        if(loginUser==null){
            response.sendRedirect("/log");
            return false;
        }else if(!loginUser.equals(i)){
            response.sendRedirect("/log");
            return false;
        }else {
            return true;
        }
    }
    //在请求处理方法执行之后执行
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }
    //该方法将在整个请求结束之后，也就是在 DispatcherServlet 渲染了对应的视图之后执行。此方法主要用来进行资源清理。
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
